const { createSign, toHump, axiosFormData } = require('./utils');

// 必传参数
let PAYPARAMS = {
	appId: '',
	merchantId: '',
	outOrderNo: '',
	uid: '',
	totalAmount: '',
	subject: '',
	body: '',
	tradeTime: '',
	validTime: '',
	notifyUrl: '',
	appSecret: '',
};

module.exports.ttPay = async params => {
	if (!checkPayParams(params)) {
		return {
			code: 10001,
			msg: '缺少参数',
		};
	}
	const { appSecret, appletVersion = '2.0' } = params;
	const appletParams = {};

	// v1: tt.requestPayment
	const ttRequestPaymentOrderInfo = {
		app_id: '', //	支付分配给业务方的 id
		method: 'tp.trade.confirm',
		sign_type: 'MD5',
		timestamp: '', // 时间戳，秒
		trade_no: '', //支付订单号
		merchant_id: '',
		uid: '',
		total_amount: '',
		pay_channel: 'ALIPAY_NO_SIGN',
		pay_type: 'ALIPAY_APP',
		risk_info: JSON.stringify({}), //目前需要传入用户的真实 IP及设备id
		params: JSON.stringify({
			url: '',
		}),
	};
	// v2: tt.pay
	const ttPayOrderInfo = {
		app_id: '',
		merchant_id: '',
		timestamp: new Date().getTime(), // 时间戳，秒
		sign_type: 'MD5',
		out_order_no: '', // 商户侧订单号
		total_amount: '',
		product_code: 'pay',
		payment_type: 'direct',
		trade_type: 'H5',
		version: '2.0',
		currency: 'CNY',
		subject: '', //商户订单名称
		body: '', //商户订单详情
		uid: '',
		trade_time: '',
		valid_time: '', // 订单失效时间，单位：秒
		notify_url: '', //服务器异步通知http地址, 传alipay_url/wx_url时可不传
		risk_info: JSON.stringify({}),
	};
	if (['1.0', '2.0+'].indexOf(params.appletVersion) >= 0) {
		// tt.requestPayment
		// 如果需要兼容头条<727版本的情况，则需要预下单
		let tradeInfo = await createTrade(params);
		if (!tradeInfo || !(+tradeInfo.code === 10000)) {
			return {
				code: tradeInfo.code,
				msg: tradeInfo.msg || '支付下单错误',
			};
		}

		updateParams(params, ttRequestPaymentOrderInfo);

		ttRequestPaymentOrderInfo.trade_no = tradeInfo.trade_no;
		ttRequestPaymentOrderInfo.params = JSON.stringify({ url: params.alipayUrl });
		ttRequestPaymentOrderInfo.sign = createSign(ttRequestPaymentOrderInfo, appSecret);
		appletParams['1.0'] = JSON.stringify(ttRequestPaymentOrderInfo);
	}
	if (['2.0', '2.0+'].indexOf(params.appletVersion) >= 0) {
		updateParams(params, ttPayOrderInfo);
		if (params.wxUrl) {
			ttPayOrderInfo.wx_type = 'MWEB';
			ttPayOrderInfo.wx_url = params.wxUrl;
		}
		if (params.alipayUrl) {
			ttPayOrderInfo.alipay_url = params.alipayUrl;
		}
		ttPayOrderInfo.sign = createSign(ttPayOrderInfo, appSecret);
		appletParams['2.0'] = JSON.stringify(ttPayOrderInfo);
	}

	return appletParams;
};

/**
 * 校验参数有效性
 * @param {object} params
 */
function checkPayParams(params) {
	const keys = Object.keys(PAYPARAMS);
	let flag = true;
	for (let key of keys) {
		if (!params[key]) {
			flag = false;
			break;
		}
	}
	// v1.0必须传 alipayUrl
	if (['1.0', '2.0+'].indexOf(params.appletVersion) >= 0 && !params['alipayUrl']) {
		return false;
	}

	return flag;
}

/**
 * 更新参数
 */
function updateParams(source, target) {
	Object.keys(target).forEach(key => {
		if (source[toHump(key)]) {
			target[key] = source[toHump(key)];
		}
	});
}

/**
 * 预下单
 * @param {object} params
 */
async function createTrade(params) {
	// 预下单参数
	const createOrderInfo = {
		app_id: '',
		method: 'tp.trade.create',
		format: 'JSON',
		charset: 'utf-8',
		sign_type: 'MD5',
		timestamp: new Date().getTime(), // 时间戳，秒
		version: '1.0',
		biz_content: {
			out_order_no: '', // 商户侧订单号
			uid: '',
			merchant_id: '',
			total_amount: 1,
			currency: 'CNY',
			subject: '', //商户订单名称
			body: '', //商户订单详情
			trade_time: '',
			valid_time: '', // 订单失效时间，单位：秒
			notify_url: ``, //服务器异步通知http地址, 传alipay_url/wx_url时可不传
			risk_info: JSON.stringify({}),
		},
	};
	updateParams(params, createOrderInfo.biz_content);

	createOrderInfo.app_id = params.appId;
	createOrderInfo.sign = createSign(createOrderInfo, params.appSecret);
	let result = await axiosFormData(createOrderInfo);
	return result.response;
}
